package com.example.auth.handler;

import com.example.auth.util.JsonUtils;
import com.example.common.constant.ServiceConstants;
import com.example.common.dto.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * It is used to solve the anomaly when authenticated users access unauthorized resources
 *
 * @author cuihaida
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();
        out.write(JsonUtils.toString(Result.error(ServiceConstants.ACCESS_DENIED_EXCEPTION, "没有权限访问！")).getBytes());
        out.flush();
        out.close();
    }
}
